import { request } from "../../request/index.js"
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    // 商品收藏
    isCollect: false,
  },
  // 商品对象
  GoodsInfo: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1]
    let options = currentPage.options;
    let goods_id = options.goods_id;
    // console.log(goods_id);
    this.getGoodsList(goods_id);
  },
  // 获取商品详情数据
  async getGoodsList(goods_id) {
    let goodsObj = await request({ url: "/goods/detail", data: { goods_id } })
    this.GoodsInfo = goodsObj;;
    let collect = wx.getStorageSync("collect") || [];
    let isCollect = collect.some(v => v.goods_id === this.GoodsInfo.goods_id)
    console.log(isCollect)
    // console.log(res)
    this.setData({
      goodsObj: {
        pics: goodsObj.pics,
        goods_price: goodsObj.goods_price,
        goods_name: goodsObj.goods_name,
        goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, '.jpg')
      }
    })
    // console.log(goodsObj)
  },
  // 点击图片 预览
  handlePrevewImage(e) {
    // console.log("预览")
    let urls = this.GoodsInfo.pics.map(v => v.pics_mid)
    let current = e.currentTarget.dataset.url
    console.log(current)
    // console.log(urls)
    console.log(e)
    wx.previewImage({
      current,
      urls
    })
  },
  // 点击添加到购物车
  handleItemAdd() {
    let cart = wx.getStorageSync("cart") || [];
    console.log(cart)
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id)
    if (index === -1) {
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo)
    } else {
      cart[index].num++
    }
    wx.setStorageSync("cart", cart);
    wx.showToast({
      title: '添加购物车成功',
      icon: 'success',
      mask: true
    });

  },
  // 点击收藏
  handleCollect() {
    let isCollect = false;
    let collect = wx.getStorageSync("collect") || [];
    let index = collect.findIndex(v => v.goods_id === this.GoodsInfo.goods_id);
    // index !==-1 表示已经收藏过
    if (index !== -1) {
      // 已经收藏过，删除
      collect.splice(index, 1);
      isCollect = false;
      wx.showToast({
        title: '已取消收藏',
        icon: 'success',
        mask: true
      });
    } else {
      // 没有被收藏，添加
      collect.push(this.GoodsInfo)
      isCollect = true;
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        mask: true
      });
    }
    // 把数组存入到缓存中
    wx.setStorageSync("collect", collect);
    this.setData({ isCollect })
  }
})